import requests
import hashlib
import urllib.parse
import time

def get_center(paths):
    flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
    pos_list = flatten(list(map(lambda path: path.split(";"), paths.split("|"))))
    lng_list = list(map(lambda pos: float(pos.split(",")[0]), pos_list))
    lat_list = list(map(lambda pos: float(pos.split(",")[1]), pos_list))
    min_lng = min(lng_list)
    max_lng = max(lng_list)
    min_lat = min(lat_list)
    max_lat = max(lat_list)
    return "%.6f,%.6f" %((min_lng + max_lng) / 2, (min_lat + max_lat) / 2), paths#.split("|")[0]

def route_map(AK, SK, paths):
    # AK = "Rope6YYZHlB4gMpInVaT8eF3wggmuHI1"
    # SK = "6rHZETSjjyEOIQBjLykK2fnTsGc5vMO4"
    # center, paths = get_center(paths)
    # base_url = "https://api.map.baidu.com/direction/v2/driving"
    # base_url = "https://api.map.baidu.com/staticimage/v2/"
  
    # # 生成SN签名
    # query = {
    #     'center': center,
    #     #'scaler': 2,
    #     #'paths' : paths,
    #     'ak': AK,
    #     'sk': SK,
    #     'timestamp': str(int(time.time()))
    # }
    # encoded_str = urllib.parse.urlencode(query)
    # raw_str = f"/dstaticimage/v2?{encoded_str}{SK}"
    # sn = hashlib.md5(urllib.parse.quote_plus(raw_str).encode()).hexdigest()
  
    # # 带SN的请求URL
    # url = f"{base_url}?{encoded_str}&sn={sn}"
    def generate_sn(params, SK):
        # 修正1：严格按参数名ASCII排序
        sorted_params = sorted(params.items(), key=lambda x: x[0].lower())
    
        # 修正2：双重编码处理
        query_string = '&'.join(
            f"{k}={urllib.parse.quote_plus(str(v))}" 
            for k, v in sorted_params
        )
    
        # 修正3：添加SK后进行MD5计算
        whole_str = urllib.parse.quote_plus(query_string + SK)
        md5 = hashlib.md5()
        md5.update(whole_str.encode('utf-8'))
        return md5.hexdigest()

    params = {
        'ak': AK,
        #'center': center,
        #'paths': paths,
        #'scaler': scaler,
        'timestamp': str(int(time.time()))
    }

    # 生成签名前强制转换scaler为字符串（文档要求）
    # params['scaler'] = str(params['scaler'])

    # 生成SN并添加
    params['sn'] = generate_sn(params, SK)

    # 构建最终URL（保留参数原始类型）
    url = "https://api.map.baidu.com/staticimage/v2?" + "&".join(
        f"{k}={urllib.parse.quote_plus(str(v))}" 
        for k, v in params.items()
    )
  
    print ("url", url)
    response = requests.get(url)
    # 假设response.text已经是乱码的形式
    html_content = response.text

    # 如果你知道原始的编码是ISO-8859-1，而实际应该是UTF-8，可以这样做：
    correctly_decoded_html = html_content.encode('iso-8859-1').decode('utf-8')

    # 现在你应该能看到正确的中文字符
    print (correctly_decoded_html)
    print (type(correctly_decoded_html))
